import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Editor from './Editor';
import s from './DraftEditor.less';

class DraftEditor extends Component {
    static defaultProps = {
        placeholder: '',
        content: '',
        tools: {
            link: false,
            font: true,
            color: true,
        },
        className: '',
        style: {},
    };

    static propTypes = {
        className: PropTypes.string,
        style: PropTypes.object,
        onCancel: PropTypes.func.isRequired,
        onSave: PropTypes.func.isRequired,
        placeholder: PropTypes.string,
        content: PropTypes.string,
        tools: PropTypes.shape({
            link: PropTypes.bool,
            font: PropTypes.bool,
            color: PropTypes.bool,
        }),
    };

    componentDidMount() {
        const topBanner = 0.86 * parseInt(document.documentElement.style.fontSize, 10);
        window.scrollTo(0, topBanner);
        this.page = document.querySelector('.curPage');
        this.page.style.maxHeight = '100vh';
        this.page.style.overflow = 'hidden';
    }

    componentWillUnmount() {
        this.page.style.maxHeight = 'auto';
        this.page.style.overflow = 'auto';
    }

    handleSave = () => {
        const html = this.editor.getCurrentHTML();
        this.props.onSave(html);
    };

    handleCancel = () => {
        this.props.onCancel();
    };

    render() {
        const {
            content, placeholder, tools, className, style, onSave, onCancel, ...otherProps
        } = this.props;
        // 生成HTML的时候空block会作为<p><br/></p>输出，多出的<br/>会导致编辑器多显示一个空行
        // 旧版编辑器保存的内容也存在输出的<br/>
        const prehandledContent = content.replace(/<br\/?>/g, '');
        return (
            <div
                ref={node => {
                    this.container = node;
                }}
                className={classnames(s.root, { [className]: className })}
                style={style}
                {...otherProps}
            >
                <div className={s.actions}>
                    <span className={s.cancel} onClick={this.handleCancel}>
                        取消
                    </span>
                    <span className={s.save} onClick={this.handleSave}>
                        保存
                    </span>
                </div>
                <Editor
                    ref={node => {
                        this.editor = node;
                    }}
                    content={prehandledContent}
                    placeholder={placeholder}
                    tools={tools}
                />
            </div>
        );
    }
}

export default DraftEditor;
